import sys

class M3u8:
    TargetDuration = "#EXT-X-TARGETDURATION:"
    MediaSeq = "#EXT-X-MEDIA-SEQUENCE:"
    Discontinuity = "#EXT-X-DISCONTINUITY"
    
    def __init__(self):
        self.header = {}
        
        self.TS_list = []   # list of lists: [TS, meta], [DISC] 
        
    def InitHeader(self, targetDuration, initSeq):
        self.header[M3u8.TargetDuration] = targetDuration
        self.header[M3u8.MediaSeq] = initSeq
        
    def InsertTS(self, ts_File, meta):
        self.TS_list.append( [ts_File, meta] )
        
    def InsertDiscontuinity(self):
        self.TS_list.append( [M3u8.Discontinuity] )
    
    def ExtendTS(self, tsList):
        self.TS_list.extend(tsList)
        
    def GetFirstTS(self):
        return self.GetTS(0)
    
    def GetTS(self, index):
        try:
            ts_data = self.TS_list[index]
            return ts_data[0]
        except IndexError:
            sys.stderr.write("Get TS : Index out of bounds: " + str(index) )
        
    def Write(self, stream):
        stream.write("#EXTM3U" + "\n")
        for meta,value in self.header.iteritems():
            line = meta + str(value) + "\n"
            stream.write(line)
            
        for ts_data in self.TS_list:
            if len(ts_data) == 2:
                stream.write(ts_data[1])    #meta
                stream.write("\n")
                stream.write(ts_data[0] + "\n")    #ts file
            else:
                stream.write(ts_data[0])    #only 1 item: Should be DISCONTUINITY
                stream.write("\n")
    
    def output(self):
        print "Header info:"
        print self.header
        
        print "TS info:"
        print self.TS_list
    
